import bannerSlider from './template/houseImgSlide.vue';
import houseAllocation from './template/houseAllocation.vue';
// import aMap from '@/components/aMap.vue';
import AMap from 'AMap';

import recommendHouse from './template/recommendHouse.vue';
import calendar from '@/pages/calendar/calendar.vue';
import dateTools from '@/components/dateTools.vue';
// import houseBottom from './template/houseBottom.vue';
import { Toast, MessageBox } from 'mint-ui';
import { reLoginWX,getQueryString } from '@/util/util.js';
import {mapMutations,mapState} from 'Vuex';
// import wx from 'weixin-js-sdk';   //微信sdk

export default {
  name: "houseDetail",
  data: () => ({
    houseId:'',
    houseKeywords:[],
    isShow:false,
    houseInfo:'',     //房源详情
    housePicList:[],  //房源图片集
    houseRentConfigList:[],     //房源配备
    recommendedHouseList:[],    //推荐房源
    lng:'',
    lat:'',
    isCollection:false,     //是否已收藏
    collectImg:'',      //收藏图标
    token:'',   //用户token
    linkMobile:'',
    trainDateFullList:['20180702','20180712'],  //（需要特定操作的完整日期部分，可以直接传日期数组（1-30）例如['20180102','20120312']）
    inviteMobile:'',
    currentPage:'',     //存放当前的地址，作为替换
  }),
  computed: {
    ...mapState({
      currentPage:state=>state.house.currentPage,
    })
  },
  methods: {
    ...mapMutations([
      'setRentDateList',
      'setCurrentPage',
    ]),
    // 日历事件
    topDateFun2(data) {
      console.log(data);
    },
    // 联系房东
    callLandlord(){
      window.location.href = 'tel://'+this.linkMobile;
    },
    showmore() {
      this.isShow = true;
      console.log(this.isShow);
    },
    // 获取房源详情
    getHouseDetail() {
      var that = this;
      // var token = that.global.global.token;
      var houseParam = {
        houseId:that.houseId
      }
      network.get(configUrl.HOUSEDETAIL_URL,houseParam,function(res){
        console.log(res);
        if(res.code==401) {
          reLoginWX();
        }else{
          var house = res.data.house;
          that.houseInfo = house;
          that.housePicList = res.data.housePicList;
          that.recommendedHouseList = res.data.recommendedHouseList;
          that.houseKeywords = res.data.houseTagList;
          that.center = [house.lng,house.lat];
          that.isCollection = res.data.isCollection;
          that.houseRentConfigList = res.data.houseRentConfigList;
          if(house.state==4){   //转租的房源有房东电话
            that.linkMobile = res.data.linkMobile;
          }
          // 收藏
          if(res.data.isCollection){
            that.collectImg = require('@/assets/images/collected@2x.png');
          }else{
            that.collectImg = require('@/assets/images/collect2@2x.png');
          }
          if (house.rentType==2) {
            let houseId = house.houseId;
            // 短租房源已租列表
            network.get(configUrl.SHORTRENTHOUSEFREEDATE_URL,{
              houseId:houseId,
              startDate:'',
              months:4,
            },function (res) {
              console.log(res);
              // that.trainDateFullList = res.dataList;
              let trainDateList = [];
              let allDateList = [];
              let dataList = res.dataList;    //所有已租时间段数组
              for (let i = 0; i < dataList.length; i++) {
                let dayNum = dataList[i].dayNum;    //每个时间段有几天
                let startDay = dataList[i].startDay;  //每个时间段的入住时间
                let daySplit = startDay.split('-');
                trainDateList[i] = daySplit[0]+daySplit[1]+daySplit[2];
                allDateList[i] = [];
                for (var j = 0; j < dayNum; j++) {
                  allDateList[i][j] = parseFloat(trainDateList[i])+j;
                }
              }

              let trainDateFullList = [];
              for (var i = 0; i < allDateList.length; i++) {
                trainDateFullList = trainDateFullList.concat(allDateList[i]);
              }
              console.log([...new Set(trainDateFullList)]);//数组去重
              that.trainDateFullList = ''+[...new Set(trainDateFullList)];
              that.setRentDateList([...new Set(trainDateFullList)]);
            },function (msg) {
              console.log(msg);
            })
          }
        }
      },function(err){
        console.log(err);
      });
    },
    // 收藏
    collectCK(){
      var that = this;
      var isCollect = that.isCollection;
      var token = that.token;
      console.log(token);
      if(token=='null'||token==undefined){
        console.log('您未登录');
        MessageBox.alert('您还未登录，请先登录?').then(action => {
          that.$router.push({ name:'login'});
        });

        return false;
      }
      var collectParam = {
        token:token,
        houseId:that.houseId
      }
      if(isCollect){
        that.collectImg = require('@/assets/images/collect2@2x.png');
        console.log('取消收藏');
        network.post(configUrl.CANCELCOLLECTIONHOUSE_URL,collectParam,function(res){
          console.log(res);
          if(res.code==401) {
            reLoginWX();
          }else{
            Toast('取消收藏');
          }
        },function(err){
          console.log(err);
        });
      }else {
        that.collectImg = require('@/assets/images/collected@2x.png');
        network.post(configUrl.COLLECTIONHOUSE_URL,collectParam,function(res){
          console.log(res);
          if(res.code==401) {
            reLoginWX();
          }else{
            Toast('成功收藏');
          }

        },function(err){
          console.log(err);
        });
      }
      that.isCollection = !isCollect;
    },
    // 立即预约
    toReservation() {
      var that = this;
      var isCollect = that.isCollect;
      var token = that.token;
      console.log(token);
      if(token=='null'||token==undefined){
        console.log('您未登录');
        MessageBox.alert('您还未登录，请先登录?').then(action => {
          that.$router.push({ name:'login'});
        });
        return false;
      }else{
        console.log(that.houseId);
        let houseParam = {
          houseId:that.houseId
        }
        network.get(configUrl.CHECKHOUSERESERVE_URL,houseParam,function (res) {
          console.log(res);
          that.$router.push({path: '/reservation', query: { houseId: that.houseId}})
        },function (err) {
          console.log(err);
          Toast('该房源不可预约');
        })
      }

    },
    // 立即签约
    toSignContact() {
      var that = this;
      var isCollect = that.isCollect;
      var token = that.token;
      console.log(token);
      if(token=='null'||token==undefined){
        console.log('您未登录');
        MessageBox.alert('您还未登录，请先登录?').then(action => {
          that.$router.push({ name:'login'});
        });
        return false;
      }
      that.$router.push({path: '/signContact', query: { houseId: that.houseId}})
    },
    recommendHouseLength:function (){
      return this.recommendedHouseList.length;
    },

  },
  mounted() {
    //do something after mounting vue instance
    let userInfo = JSON.parse(window.localStorage.getItem('userInfo'));
    this.token = window.localStorage.getItem('userToken');
    this.houseId = this.$route.query.houseId;    //房源id
    this.lng = this.$route.query.lng;
    this.lat = this.$route.query.lat;
    console.log(userInfo);
    this.getHouseDetail();

    let ua = navigator.userAgent.toLowerCase();
    //android终端
    let isAndroid = ua.indexOf('Android') > -1 || ua.indexOf('Adr') > -1;
　　//ios终端
    let isiOS = !!ua.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);

    let shareUrl = 'http://rh.klbkvg.cn/houseDetail?houseId='+this.houseId+'&lng='+this.lng+'&lat='+this.lat+'&mobile='+userInfo.mobile;
    let imgUrl = require('@/assets/images/logo@2x.png');
    // if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
        //ios
        // this.setCurrentPage(window.location.href);
        console.log(window.location.href);
        this.currentPage = window.location.href;
        // 替换当前的地址为shareUrl
        window.history.replaceState({}, this.houseInfo.title, shareUrl);
        // alert(window.location.href);
        // window.history.replaceState({}, document.title, shareUrl);
     // }
    let wxshareParam = {
      url:shareUrl
    }
    network.get(configUrl.WXSHAREPARAMS_URL,wxshareParam,function(res){
      console.log(res);
      // Toast('shareUrl='+shareUrl)
      //接口入住权限验证配置
       wx.config({
            // debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。

            appId: res.appId, // 必填，公众号的唯一标识
            timestamp: res.timestamp, // 必填，生成签名的时间戳
            nonceStr: res.nonceStr, // 必填，生成签名的随机串
            signature: res.signature, // 必填，签名，见附录1
            jsApiList: [
               'onMenuShareTimeline',
               'onMenuShareAppMessage',
               'onMenuShareQQ',
               'onMenuShareWeibo',
               'onMenuShareQZone'
          ] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
      });
      let shareConfig = {
        title: '随寓房源详情', // 分享标题
        desc: '随寓分享详情介绍文案', // 分享描述
        link: shareUrl, // 分享链接
        imgUrl: imgUrl, // 分享图标
        type: '', // 分享类型,music、video或link，不填默认为link
        dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
        success: function(event) {
          console.log(event);
          Toast('分享成功');
          // 用户确认分享后执行的回调函数
        },
        cancel: function(error) {
          console.log(error);
            // 用户取消分享后执行的回调函数
        }
      }
      wx.ready(function() {
           wx.onMenuShareAppMessage(shareConfig);
          wx.onMenuShareTimeline(shareConfig);
      });
    },function(err){
      console.log(err);
    });

  },
  components: {
    bannerSlider,
    houseAllocation,
    aMap:()=>import('@/components/aMap.vue'),
    recommendHouse,
    calendar,
    dateTools,
    // houseBottom,
  },
  // 离开当前页时，还原当前页的URL（保证返回正常）
  beforeRouteLeave(to, from, next) {
      window.history.replaceState({}, '', this.currentPage)
      next()
  },

  beforeRouteEnter(to, from, next) {    //进入路由前
    console.log(to);
    var reg = new RegExp("(^|&)"+ 'mobile' +"=([^&]*)(&|$)");   //正则拆分地址参数mobile
    let toFullPath = to.fullPath;     //进入页面的路由地址，判断没有电话号码的时候不是推荐进来的
    let url = toFullPath.split('?');
    let result =  url[1].match(reg);
    console.log(result);

    if (result == null || result==undefined) {
      console.log('不是推荐的');
    }else {
      console.log('推荐过来的');
      let inviteMobile = decodeURIComponent(result[2]);
      window.localStorage.setItem('inviteMobile',inviteMobile);
      // self.setInviteMobile(inviteMobile);   //推荐者手机号存到vuex(还未进入页面，还没有this——vue对象)

    }

    next();
  }

}
